package com.software.sqlite.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.software.sqlite.api.admin.v1.vo.AdminV1Result;
import com.software.sqlite.api.app.v1.vo.AppV1Result;
import com.software.sqlite.entity.*;
import com.software.sqlite.ftp.FTPDownloadWithProgress;
import com.software.sqlite.ftp.FTPModel;
import com.software.sqlite.mapper.*;
import com.software.sqlite.service.ITaskService;
import com.software.sqlite.task.ApiTask;
import com.software.sqlite.task.MovieWalletScheduledTask;
import com.software.sqlite.utils.CommonUtils;
import com.software.sqlite.utils.DateUtils;
import com.software.sqlite.utils.FileUtils;
import com.software.sqlite.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class TaskService implements ITaskService {

    @Resource
    private YstMovieService ystMovieService;
    @Resource
    private TbMovieServerService movieServerService;
    @Resource
    private TbMovieMapper movieMapper;
    @Resource
    private TbMovieUserMapper movieUserMapper;
    @Resource
    private TbMovieServerMapper movieServerMapper;
    @Resource
    private TbMovieUserBillMapper movieUserBillMapper;
    @Resource
    private TbProductInfoMapper productInfoMapper;
    @Resource
    private TbMovieTypeMapper movieTypeMapper;
    @Value("${shore.cloud.url}")
    private String shoreCloudUrl;
    @Value("${file.film.dangjian}")
    private String dangjianDir;
    @Value("${file.film.zongyi}")
    private String zongyiDir;
    @Value("${file.film.movie}")
    private String movieDir;
    @Value("${ftp-server.ip}")
    private String ftpIp;
    @Value("${ftp-server.port")
    private String ftpPort;
    @Value("${ftp-server.username}")
    private String ftpUsername;
    @Value("${ftp-server.password}")
    private String ftpPassword;
    @Value("${ftp-server.homeDirectory}")
    private String ftpHomeDirectory;
    @Value("${ship.log}")
    private String logDir;

    @Override
    public FTPModel ftpDownloadFile(String remoteFile, String localFile) {
        FTPModel result = new FTPModel();
        try {
            Integer port=CommonUtils.parseIntegerData(ftpPort,27);
            FTPDownloadWithProgress.download(ftpIp,port,ftpUsername,ftpPassword,remoteFile,ftpHomeDirectory+localFile);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            result.setLocalFile(localFile);
            result.setRemoteFile(remoteFile);
            result.setTotalSize(FTPDownloadWithProgress.totalSize);
            result.setDoneSize(FTPDownloadWithProgress.doneSize);
        }
        return result;
    }

    @Override
    public boolean autoSynchronyMovies() {
        boolean result=false;
        try {
            if(!ApiTask.isRunning) {
                ApiTask.isRunning = true;
                TbMovieServer movieServer = new TbMovieServer();
                List<TbMovieServer> list = movieServerService.selectList(movieServer);
                if (list.size() > 0) {
                    String shipServerUrl = list.get(0).getServerUrl();
                    Map<String, Object> regitsterDeviceParams = new LinkedHashMap<>();
                    /**
                     * {
                     * 	"C": "Device",
                     * "D": {
                     * "IP": "192.168.1.1",
                     * "MAC": "DD:DD:DD:DD:DD:DD",
                     * "ModelNo": "BOX-002",
                     * "Title": "BOX-002",
                     * "UniqueCode": "b562e3d8a4314e9e9ae6c3648855b2e2",
                     * "Version": 1.23
                     * },
                     * "F": "Regdevice",
                     * "M": "DD:DD:DD:DD:DD:DD",
                     * "U": "b562e3d8a4314e9e9ae6c3648855b2e2"
                     * }
                     */
                    regitsterDeviceParams.put("C", "Device");
                    Map<String, Object> D = new LinkedHashMap<>();
                    D.put("IP", "192.168.1.1");
                    D.put("MAC", "DD:DD:DD:DD:DD:DD");
                    D.put("ModelNo", "BOX-001");
                    D.put("Title", "BOX-001");
                    D.put("UniqueCode", "00000000000000000000000000000000");
                    D.put("Version", 1.23);
                    regitsterDeviceParams.put("D", D);
                    regitsterDeviceParams.put("F", "Regdevice");
                    regitsterDeviceParams.put("M", "DD:DD:DD:DD:DD:DD");
                    regitsterDeviceParams.put("U", "b562e3d8a4314e9e9ae6c3648855b2e2");
                    String regitsterDeviceShipServerResult = ystMovieService.getRegitsterDeviceShipServer(shipServerUrl, regitsterDeviceParams);
                    log.info("========RegitsterDeviceShipServerResult====" + regitsterDeviceShipServerResult);
                    if (CommonUtils.isNotBlank(regitsterDeviceShipServerResult) && regitsterDeviceShipServerResult.indexOf("State")>0) {
                        /**
                         * 1、影片分类
                         */
                        /**
                         * {
                         * 	"mac": "DD:DD:DD:DD:DD:DD",
                         *  "filmsource": "2"
                         * }
                         */
                        Map<String, Object> groupTypeListParams = new LinkedHashMap<>();
                        groupTypeListParams.put("mac", "DD:DD:DD:DD:DD:DD");
                        groupTypeListParams.put("filmsource", "2");
                        String groupTypeListResult=ystMovieService.getGroupTypeListByShipServer(shipServerUrl, groupTypeListParams);
                        log.info("groupTypeListResult---"+groupTypeListResult);
                        //{"state":true,"data":[{"title":"类型","cate":[{"name":"全部","tid":"0"},{"name":"动作","tid":"2"},{"name":"犯罪","tid":"6"},{"name":"冒险","tid":"7"},{"name":"悬疑","tid":"8"},{"name":"战争","tid":"13"},{"name":"惊悚","tid":"3"},{"name":"喜剧","tid":"4"},{"name":"爱情","tid":"5"},{"name":"家庭","tid":"9"},{"name":"科幻","tid":"10"},{"name":"恐怖","tid":"12"},{"name":"动画","tid":"16"}]},{"title":"地区","cate":[{"name":"全部","tid":"0"},{"name":"中国大陆","tid":"280"},{"name":"美国","tid":"17"},{"name":"韩国","tid":"26"},{"name":"中国香港","tid":"20"},{"name":"中国台湾","tid":"282"},{"name":"日本","tid":"24"},{"name":"英国","tid":"28"},{"name":"法国","tid":"34"},{"name":"德国","tid":"38"},{"name":"意大利","tid":"149"},{"name":"俄罗斯","tid":"220"},{"name":"其它","tid":"25"}]},{"title":"时间","cate":[{"name":"全部","tid":"0"},{"name":"2023","tid":"295"},{"name":"2022","tid":"291"},{"name":"2021","tid":"286"},{"name":"2020","tid":"287"},{"name":"2019","tid":"288"},{"name":"更早","tid":"32"}]}],"info":""}
                        if (CommonUtils.isNotBlank(groupTypeListResult) && groupTypeListResult.indexOf("state")>0) {
                            YstMovieResult groupTypeListData = JSON.parseObject(groupTypeListResult, YstMovieResult.class);
                            if (groupTypeListData != null && groupTypeListData.isState()) {
                                TbMovieType typeModel = new TbMovieType();
                                List<TbMovieType> typeList = movieTypeMapper.selectListBySQL(typeModel);
                                Map<String, TbMovieType> typeMap = new HashMap<>();
                                if (typeList.size() > 0) {
                                    for (TbMovieType mtModel : typeList) {
                                        typeMap.put(mtModel.getTitle(), mtModel);
                                    }
                                }
                                List groupTypeList = JSON.parseArray(CommonUtils.parseStringData(groupTypeListData.getData()), Map.class);
                                for (int i = 0; i < groupTypeList.size(); i++) {
                                    Map<String, Object> mp = (Map<String, Object>) groupTypeList.get(i);
                                    TbMovieType movieType = new TbMovieType();
                                    if (mp.get("title").equals("类型")) {
                                        movieType.setCode("leixing");
                                        movieType.setTitle("类型");
                                        movieType.setCate(CommonUtils.parseStringData(mp.get("cate")));
                                    } else if (mp.get("title").equals("地区")) {
                                        movieType.setCode("diqu");
                                        movieType.setTitle("地区");
                                        movieType.setCate(CommonUtils.parseStringData(mp.get("cate")));
                                    } else if (mp.get("title").equals("时间")) {
                                        movieType.setCode("shijian");
                                        movieType.setTitle("时间");
                                        movieType.setCate(CommonUtils.parseStringData(mp.get("cate")));
                                    }
                                    movieType.setUseStatus("normal");
                                    movieType.setCreateAdminId(0L);
                                    movieType.setCreateTime(new Date());
                                    movieType.setUpdateAdminId(0L);
                                    movieType.setUpdateTime(new Date());
                                    if (typeMap.containsKey(movieType.getTitle())) {
                                        movieType = typeMap.get(movieType.getTitle());
                                        movieType.setCate(CommonUtils.parseStringData(mp.get("cate")));
                                        movieTypeMapper.updateByPrimaryKey(movieType);
                                    } else {
                                        movieTypeMapper.insert(movieType);
                                    }
                                }
                            }
                        } else {
                            log.info("===================GetGroupTypeListByShipServer Fail=====================");
                        }


                        /**
                         * 2、分类获取影⽚
                         * mac=DD:DD:DD:DD:DD:DD
                         * filmsource=2
                         * leixing=0
                         * diqu=0
                         * shijian=0
                         */
                        Map<String, Object> getFilmListByTypeParams = new LinkedHashMap<>();
                        getFilmListByTypeParams.put("mac", "DD:DD:DD:DD:DD:DD");
                        getFilmListByTypeParams.put("filmsource", "2");
                        String getFilmListByTypeResult=ystMovieService.getFilmListByTypeByShipServer(shipServerUrl, getFilmListByTypeParams);
                        //{"state":true,"data":[{"movieId":"17013","displayName":"毕业第一年","shotDesc":"","score":6.7,"posterLocalImg":"http://192.168.233.128/film/images/1700976160_36522622W1.jpg","videoType":"|4|5|1|","shortPinYin":"bydyn","audioType":"","filmLimit":"0"},{"movieId":"16936","displayName":"生命底色","shotDesc":"","score":6,"posterLocalImg":"http://192.168.233.128/film/images/1700136411_36123302W1.jpg","videoType":"|1|","shortPinYin":"smds","audioType":"","filmLimit":"0"},{"movieId":"16782","displayName":"战俘拳王","shotDesc":"","score":7.8,"posterLocalImg":"http://192.168.233.128/film/images/1695867173_34945502W1.jpg","videoType":"|33|1|","shortPinYin":"zfqw","audioType":"","filmLimit":"0"},{"movieId":"16937","displayName":"93国际列车大劫案：莫斯科行动","shotDesc":"","score":8.1,"posterLocalImg":"http://192.168.233.128/film/images/1700135438_10810266W1.jpg","videoType":"|2|6|1|7|3|","shortPinYin":"93gjlcdjamskxd","audioType":"","filmLimit":"0"},{"movieId":"16781","displayName":"神兽魔王大作战","shotDesc":"","score":6.8,"posterLocalImg":"http://192.168.233.128/film/images/1700051594_34870099W1.jpg","videoType":"|11|2|7|","shortPinYin":"ssmwdzz","audioType":"","filmLimit":"0"},{"movieId":"16911","displayName":"爱与怪物","shotDesc":"","score":8.1,"posterLocalImg":"http://192.168.233.128/film/images/1699939620_21349338W1.jpg","videoType":"|4|10|11|2|7|","shortPinYin":"aygw","audioType":"","filmLimit":"0"},{"movieId":"16605","displayName":"幸福小马灯","shotDesc":"","score":6.1,"posterLocalImg":"http://192.168.233.128/film/images/1699260498_36577026W1.jpg","videoType":"|4|5|1|","shortPinYin":"xfxmd","audioType":"","filmLimit":"0"},{"movieId":"16754","displayName":"哆啦A梦：大雄与天空的理想乡-国语版","shotDesc":"","score":7.7,"posterLocalImg":"http://192.168.233.128/film/images/1699782412_35967711W1.jpg","videoType":"|16|","shortPinYin":"dlmdxytkdlxx","audioType":"","filmLimit":"0"},{"movieId":"16753","displayName":"哆啦A梦：大雄与天空的理想乡","shotDesc":"","score":7.7,"posterLocalImg":"http://192.168.233.128/film/images/1699782412_35967711W1.jpg","videoType":"|16|","shortPinYin":"dlmdxytkdlxx","audioType":"","filmLimit":"0"},{"movieId":"16714","displayName":"甜心女孩","shotDesc":"","score":7.6,"posterLocalImg":"http://192.168.233.128/film/images/1699263345_34778519W1.jpg","videoType":"|2|3|1|","shortPinYin":"txnh","audioType":"","filmLimit":"0"}],"info":""}
                        log.info("getFilmListByTypeResult---"+getFilmListByTypeResult);
                        if (CommonUtils.isNotBlank(getFilmListByTypeResult) && getFilmListByTypeResult.indexOf("state")>0) {
                            TbMovie movie = new TbMovie();
                            Map<Long, TbMovie> movieMap = new HashMap<>();
                            List<TbMovie> movieList = movieMapper.selectListBySQL(movie);
                            if (movieList.size() > 0) {
                                for (TbMovie item : movieList) {
                                    movieMap.put(item.getMovieId(), item);
                                }
                            }
                            YstMovieResult filmListByTypeData = JSON.parseObject(getFilmListByTypeResult, YstMovieResult.class);
                            if (filmListByTypeData != null && filmListByTypeData.isState()) {
                                List filmListByTypeList = JSON.parseArray(CommonUtils.parseStringData(filmListByTypeData.getData()), Map.class);
                                for (int i = 0; i < filmListByTypeList.size(); i++) {
                                    Map<String, Object> resultMp = (Map<String, Object>) filmListByTypeList.get(i);
                                    Long movieId = CommonUtils.parseLongData(resultMp.get("movieId"));
                                    String displayName = CommonUtils.parseStringData(resultMp.get("displayName"));
                                    String shotDesc = CommonUtils.parseStringData(resultMp.get("shotDesc"));
                                    String score = CommonUtils.parseStringData(resultMp.get("score"));
                                    String posterLocalImg = CommonUtils.parseStringData(resultMp.get("posterLocalImg"));
                                    String movieImg="";
                                    try {
                                        HttpUtil.downloadFile(posterLocalImg,movieDir+File.separator+movieId+".jpg");
                                        movieImg=movieId+".jpg";
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                    String videoType = CommonUtils.parseStringData(resultMp.get("videoType"));
                                    String shortPinYin = CommonUtils.parseStringData(resultMp.get("shortPinYin"));
                                    String audioType = CommonUtils.parseStringData(resultMp.get("audioType"));
                                    String filmLimit = CommonUtils.parseStringData(resultMp.get("filmLimit"));
                                    String person = "";
                                    String duration = "";
                                    String producePlace = "";
                                    String videoPath = "";
                                    String description = "";
                                    String director = "";
                                    String movieType = "";
                                    String filmSource = "";
                                    String remark = JSON.toJSONString(resultMp);
                                    Map<String, Object> getFilmDetailParams = new LinkedHashMap<>();
                                    getFilmDetailParams.put("mac", "DD:DD:DD:DD:DD:DD");
                                    getFilmDetailParams.put("filmsource", "2");
                                    getFilmDetailParams.put("movieId", movieId);
                                    //{"state":true,"data":{"movieId":"16936","displayName":"生命底色","shotDesc":"","score":6,"posterLocalImg":"http://192.168.233.128/film/images/1700136411_36123302W1.jpg","videoType":"","playTimes":0,"person":"李泽华","duration":90,"producePlace":"中国大陆","videoPath":"","description":"　　电影《生命底色》是根据彝族女作家白菊秋女(商小燕)的长篇小说《紫蝴蝶》改编。影片讲述了中国四川山区大凉山下的月亮湾中学女教师尚玉和她的两代学生因贫辍学而又重返校园的故事。","director":"商小燕","movieType":"剧情","audioType":"","filmSource":6},"info":""}
                                    String getFilmDetailResult = ystMovieService.getFilmDetailByShipServer(shipServerUrl, getFilmDetailParams);
                                    log.info("getFilmDetailResult---"+getFilmDetailResult);
                                    if (CommonUtils.isNotBlank(getFilmDetailResult) && getFilmDetailResult.indexOf("state")>0) {
                                        YstMovieResult filmDetailData = JSON.parseObject(getFilmDetailResult, YstMovieResult.class);
                                        if (filmDetailData != null && filmDetailData.isState()) {
                                            Map<String, Object> filmDetailMap = (Map<String, Object>) filmDetailData.getData();
                                            duration = CommonUtils.parseStringData(filmDetailMap.get("duration"));
                                            producePlace = CommonUtils.parseStringData(filmDetailMap.get("producePlace"));
                                            videoPath = CommonUtils.parseStringData(filmDetailMap.get("videoPath"));
                                            description = CommonUtils.parseStringData(filmDetailMap.get("description"));
                                            director = CommonUtils.parseStringData(filmDetailMap.get("director"));
                                            movieType = CommonUtils.parseStringData(filmDetailMap.get("movieType"));
                                            filmSource = CommonUtils.parseStringData(filmDetailMap.get("filmSource"));
                                            person = CommonUtils.parseStringData(((Map<?, ?>) filmDetailData.getData()).get("person"));
                                            remark = CommonUtils.parseStringData(filmDetailData.getData());
                                        }
                                    }
                                    TbMovie movieModel = new TbMovie();
                                    movieModel.setMovieId(movieId);
                                    movieModel.setAmount(new BigDecimal(0));
                                    movieModel.setDisplayName(displayName);
                                    movieModel.setScore(score);
                                    movieModel.setPosterLocalImg(posterLocalImg);
                                    movieModel.setMovieImg(movieImg);
                                    movieModel.setShortPinYin(shortPinYin);
                                    movieModel.setShotDesc(shotDesc);
                                    movieModel.setDuration(duration);
                                    movieModel.setProducePlace(producePlace);
                                    movieModel.setDescription(description);
                                    movieModel.setDirector(director);
                                    movieModel.setMovieType(movieType);
                                    movieModel.setPerson(person);
                                    movieModel.setRemark(remark);
                                    movieModel.setUseStatus("normal");
                                    movieModel.setCreateAdminId(0L);
                                    movieModel.setCreateTime(new Date());
                                    movieModel.setUpdateAdminId(0L);
                                    movieModel.setUpdateTime(new Date());
                                    if (movieMap.containsKey(movieId)) {
                                        TbMovie exitModel = movieMap.get(movieId);
                                        movieModel.setCreateTime(exitModel.getCreateTime());
                                        movieModel.setAmount(exitModel.getAmount());
                                        movieMapper.updateByPrimaryKey(movieModel);
                                        movieMap.remove(movieId);
                                    } else {
                                        movieMapper.insert(movieModel);
                                    }

                                }

                                if(movieMap.size()>0){
                                    for (Map.Entry<Long, TbMovie> entry:movieMap.entrySet()) {
                                        TbMovie tbMovie=entry.getValue();
                                        if(tbMovie!=null){
                                            movieMapper.deleteByMovieId(tbMovie.getMovieId());
                                        }
                                    }
                                }
                            }
                        } else {
                            log.info("===================GetFilmListByTypeByShipServer Fail=====================");
                        }

                    } else {
                        log.info("===================GetRegitsterDeviceShipServer Fail=====================");
                    }
                } else {
                    log.info("===================没有服务器配置=====================");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ApiTask.isRunning=false;
        }
        return result;
    }

    @Override
    public boolean autoSynchronyCloud() {
        boolean result=false;
        try{
            if(!ApiTask.isCloudRunning) {
                ApiTask.isCloudRunning = true;
                TbMovieServer movieServerModel=null;
                List<TbMovieServer> movieServerList=movieServerMapper.selectListBySQL(new TbMovieServer());
                if(movieServerList.size()>0){
                    movieServerModel=movieServerList.get(0);
                }
                if(movieServerModel==null){
                    log.error("movieServer is null...");
                }else{
                    TbMovie movieModel = new TbMovie();
                    List<TbMovie> movieList = movieMapper.selectListBySQL(movieModel);
                    TbMovieUserBill movieUserBillModel = new TbMovieUserBill();
                    movieUserBillModel.setBillType("out");
                    movieUserBillModel.setDataResource("ship");
                    List<TbMovieUserBill> movieUserBillList = movieUserBillMapper.selectListBySQL(movieUserBillModel);
                    TbMovieUser movieUserModel = new TbMovieUser();
                    List<TbMovieUser> movieUserList = movieUserMapper.selectListBySQL(movieUserModel);
                    Map<String, String> resultMap = new HashMap<>();
                    resultMap.put("movieList", JSON.toJSONString(movieList));
                    resultMap.put("movieUserBillList", JSON.toJSONString(movieUserBillList));
                    resultMap.put("movieUserList", JSON.toJSONString(movieUserList));
                    try {
                        HttpRequest request = HttpUtil.createPost(shoreCloudUrl + "/cloud/v1/synchronyCloud");
                        Map<String,Object> params=new HashMap<>();
                        params.put("appKey","movie12qwaszx34erdfcv");
                        params.put("appSecret","abc12332111223333");
                        params.put("keyWord",JSON.toJSONString(resultMap));
                        params.put("shipId",movieServerModel.getShipId());
                        request.form(params);
                        HttpResponse execute = request.execute();
                        if (!execute.isOk()) {
                            log.error("请求token失败,body={},execute={}", execute.body(), execute);
                        }
                        String resultString= UnicodeUtil.toString(execute.body());
                        if(CommonUtils.isNotBlank(resultString)){
                            AppV1Result appV1Result=JSON.parseObject(resultString,AppV1Result.class);
                            if(appV1Result.isSuccess()){
                                Map<String,Object> resultMp= (Map<String, Object>) appV1Result.getData();
                                String movieListString=CommonUtils.parseStringData(resultMp.get("movieList"));
                                List<TbMovie> movieListCloud= JSON.parseArray(movieListString,TbMovie.class);
                                String movieUserBillListString=CommonUtils.parseStringData(resultMp.get("movieUserBillList"));
                                List<TbMovieUserBill> movieUserBillListCloud= JSON.parseArray(movieUserBillListString,TbMovieUserBill.class);
                                String productListString=CommonUtils.parseStringData(resultMp.get("productList"));
                                List<TbProductInfo> productListCloud=JSON.parseArray(productListString,TbProductInfo.class);
                                String shipMovieListString=CommonUtils.parseStringData(resultMp.get("shipMovieList"));
                                List<TbMovie> shipMovieListCloud=JSON.parseArray(shipMovieListString,TbMovie.class);
                                //更新电影价格
                                if(movieListCloud!=null && movieListCloud.size()>0){
                                    for(TbMovie movie:movieListCloud){
                                        if(movie.getAmount()!=null){
                                            movieMapper.updateAmount(movie.getAmount(),movie.getMovieId());
                                        }
                                    }
                                }
                                //更新账单记录
                                if(movieUserBillListCloud!=null && movieUserBillListCloud.size()>0){
                                    List<TbMovieUserBill> exitMovieUserBillList=movieUserBillMapper.selectListBySQL(new TbMovieUserBill());
                                    Map<String,TbMovieUserBill> exitMovieUserBillMap=new HashMap<>();
                                    if(exitMovieUserBillList.size()>0){
                                        for(TbMovieUserBill bill:exitMovieUserBillList){
                                            exitMovieUserBillMap.put(bill.getOrderNo(),bill);
                                        }
                                    }
                                    List<TbMovieUserBill> newMovieUserBillList=new ArrayList<>();
                                    for(TbMovieUserBill bill:movieUserBillListCloud)
                                    {
                                        if(!exitMovieUserBillMap.containsKey(bill.getOrderNo()))
                                        {
                                            newMovieUserBillList.add(bill);
                                        }
                                    }
                                    if(newMovieUserBillList.size()>0)
                                    {
                                        movieUserBillMapper.insertList(newMovieUserBillList);
                                    }
                                }
                                //productList
                                if(productListCloud!=null){
                                    productInfoMapper.deleteAll();
                                    if(productListCloud.size()>0)
                                    {
                                        productInfoMapper.insertList(productListCloud);
                                    }
                                }
                                //shipMovieList
                                if(shipMovieListCloud!=null && shipMovieListCloud.size()>0)
                                {
                                    Long[] movieIdArray=new Long[shipMovieListCloud.size()];
                                    for(int i=0;i<shipMovieListCloud.size();i++)
                                    {
                                        movieIdArray[i]=shipMovieListCloud.get(i).getMovieId();
                                    }
                                    List<TbMovie> newMovieList=new ArrayList<>();
                                    Map<Long,TbMovie> exitMovieMap=new LinkedHashMap<>();
                                    List<TbMovie> exitMovieList=movieMapper.findMovieListByIds(movieIdArray);
                                    if(exitMovieList.size()>0){
                                        for(TbMovie movieItem:exitMovieList){
                                            exitMovieMap.put(movieItem.getMovieId(),movieItem);
                                        }
                                    }
                                    for(int i=0;i<shipMovieListCloud.size();i++)
                                    {
                                        TbMovie cloudMovie=shipMovieListCloud.get(i);
                                        if(!exitMovieMap.containsKey(cloudMovie.getMovieId())){
                                            newMovieList.add(cloudMovie);
                                        }
                                    }
                                    if(newMovieList.size()>0)
                                    {
                                        movieMapper.insertList(newMovieList);
                                    }
                                }
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    result = true;
                }

            }
        }catch (HttpException e){
            log.error(e.getMessage());
        }catch (Exception e){
            log.error(e.getMessage());
        }finally {
            ApiTask.isCloudRunning=false;
        }
        return result;
    }

    @Override
    public boolean autoLocalDJMovies() {
        boolean result=false;
        try{
            FileUtils.existOrmkdir(dangjianDir);
            File fileDireCtory = new File(dangjianDir);
            File[] fileList=fileDireCtory.listFiles();
            if(fileList.length>0){
                TbMovie dangjianMovie=new TbMovie();
                dangjianMovie.setMovieType("党建");
                List<TbMovie> dangjianList=movieMapper.selectListBySQL(dangjianMovie);
                Map<String,TbMovie> dangjianMap=new HashMap<>();
                if(dangjianList.size()>0){
                    for(TbMovie movie:dangjianList){
                        dangjianMap.put(movie.getFileName(),movie);
                    }
                }
                List<TbMovie> addMovieList=new ArrayList<>();
                Long movieId=CommonUtils.parseLongData(DateUtils.format(new Date(),DateUtils.YMD_DASH_WITH_MITIME_STR));
                for(File file:fileList){
                    if(!file.isDirectory()){
                        String fileName=FileUtil.getName(file);
                        String extName= FileUtil.extName(file);
                        String mainName=FileUtil.mainName(file);
                        String filePath=file.getPath();
                        TbMovie dMovie=new TbMovie();
                        dMovie.setMovieType("党建");
                        dMovie.setDisplayName(mainName);
                        dMovie.setAmount(BigDecimal.ZERO);
                        dMovie.setFileName(fileName);
                        dMovie.setExtName(extName);
                        dMovie.setMainName(mainName);
                        dMovie.setFilePath(filePath);
                        dMovie.setRemark("");
                        dMovie.setMovieId(movieId);
                        movieId=movieId-1;
                        dMovie.setUseStatus("normal");
                        dMovie.setCreateAdminId(0L);
                        dMovie.setCreateTime(new Date());
                        dMovie.setUpdateAdminId(0L);
                        dMovie.setUpdateTime(new Date());
                        if(dangjianMap.containsKey(fileName)){
                            dangjianMap.remove(fileName);
                        }else{
                            addMovieList.add(dMovie);
                        }

                    }
                }
                if(dangjianMap.size()>0){
                    Long[] movieIdArray=new Long[dangjianMap.size()];
                    Integer idx=0;
                    for(String key : dangjianMap.keySet()) {
                        TbMovie dMovie=dangjianMap.get(key);
                        if(dMovie!=null){
                            movieIdArray[idx]=dMovie.getMovieId();
                            idx++;
                        }
                    }
                    movieMapper.deleteAllDangjian(movieIdArray);
                }
                if(addMovieList.size()>0){
                    movieMapper.insertList(addMovieList);
                }
                result=true;
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return result;
    }

    @Override
    public boolean autoLocalZyMovies() {
        boolean result=false;
        try{
            FileUtils.existOrmkdir(zongyiDir);
            File fileDireCtory = new File(zongyiDir);
            File[] fileList=fileDireCtory.listFiles();
            if(fileList.length>0){
                TbMovie zongyiMovie=new TbMovie();
                zongyiMovie.setMovieType("综艺");
                List<TbMovie> zongyiList=movieMapper.selectListBySQL(zongyiMovie);
                Map<String,TbMovie> zongyiMap=new HashMap<>();
                if(zongyiList.size()>0){
                    for(TbMovie movie:zongyiList){
                        zongyiMap.put(movie.getFileName(),movie);
                    }
                }
                List<TbMovie> addMovieList=new ArrayList<>();
                Long movieId=CommonUtils.parseLongData(DateUtils.format(new Date(),DateUtils.YMD_DASH_WITH_MITIME_STR));
                for(File file:fileList){
                    if(!file.isDirectory()){
                        String fileName=FileUtil.getName(file);
                        String extName= FileUtil.extName(file);
                        String mainName=FileUtil.mainName(file);
                        String filePath=file.getPath();
                        TbMovie dMovie=new TbMovie();
                        dMovie.setMovieType("综艺");
                        dMovie.setDisplayName(mainName);
                        dMovie.setAmount(BigDecimal.ZERO);
                        dMovie.setFileName(fileName);
                        dMovie.setExtName(extName);
                        dMovie.setMainName(mainName);
                        dMovie.setFilePath(filePath);
                        dMovie.setRemark("");
                        dMovie.setMovieId(movieId);
                        movieId=movieId-1;
                        dMovie.setUseStatus("normal");
                        dMovie.setCreateAdminId(0L);
                        dMovie.setCreateTime(new Date());
                        dMovie.setUpdateAdminId(0L);
                        dMovie.setUpdateTime(new Date());
                        if(zongyiMap.containsKey(fileName)){
                            zongyiMap.remove(fileName);
                        }else{
                            addMovieList.add(dMovie);
                        }

                    }
                }
                if(zongyiMap.size()>0){
                    Long[] movieIdArray=new Long[zongyiMap.size()];
                    Integer idx=0;
                    for(String key : zongyiMap.keySet()) {
                        TbMovie dMovie=zongyiMap.get(key);
                        if(dMovie!=null){
                            movieIdArray[idx]=dMovie.getMovieId();
                            idx++;
                        }
                    }
                    movieMapper.deleteAllZongyi(movieIdArray);
                }
                if(addMovieList.size()>0){
                    movieMapper.insertList(addMovieList);
                }
                result=true;
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return result;
    }




    @Override
    public boolean synBillShipToCloud() {
        boolean result=false;
        try{
            TbMovieServer movieServerModel=null;
            List<TbMovieServer> movieServerList=movieServerMapper.selectListBySQL(new TbMovieServer());
            if(movieServerList.size()>0){
                movieServerModel=movieServerList.get(0);
            }
            if(movieServerModel==null){
                log.error("movieServer is null...");
            }else{
                TbMovieUserBill movieUserBillModel = new TbMovieUserBill();
                movieUserBillModel.setBillType("out");
                movieUserBillModel.setDataResource("ship");
                List<TbMovieUserBill> movieUserBillList = movieUserBillMapper.selectListBySQL(movieUserBillModel);
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put("movieUserBillList", JSON.toJSONString(movieUserBillList));
                try {
                    HttpRequest request = HttpUtil.createPost(shoreCloudUrl + "/cloud/v1/synBillShipToCloud");
                    Map<String,Object> params=new HashMap<>();
                    params.put("appKey","movie12qwaszx34erdfcv");
                    params.put("appSecret","abc12332111223333");
                    params.put("keyWord",JSON.toJSONString(resultMap));
                    params.put("shipId",movieServerModel.getShipId());
                    request.form(params);
                    HttpResponse execute = request.execute();
                    if (!execute.isOk()) {
                        log.error("请求token失败,body={},execute={}", execute.body(), execute);
                    }
                    String resultString= UnicodeUtil.toString(execute.body());
                    if(CommonUtils.isNotBlank(resultString)){
                        AppV1Result appV1Result=JSON.parseObject(resultString,AppV1Result.class);
                        if(appV1Result.isSuccess()){
                            Map<String,Object> resultMp= (Map<String, Object>) appV1Result.getData();
                            String movieListString=CommonUtils.parseStringData(resultMp.get("movieList"));
                            List<TbMovie> movieListCloud= JSON.parseArray(movieListString,TbMovie.class);
                            String movieUserBillListString=CommonUtils.parseStringData(resultMp.get("movieUserBillList"));
                            List<TbMovieUserBill> movieUserBillListCloud= JSON.parseArray(movieUserBillListString,TbMovieUserBill.class);
                            //更新电影价格
                            if(movieListCloud!=null && movieListCloud.size()>0){
                                for(TbMovie movie:movieListCloud){
                                    if(movie.getAmount()!=null){
                                        movieMapper.updateAmount(movie.getAmount(),movie.getMovieId());
                                    }
                                }
                            }
                            //更新账单记录
                            if(movieUserBillListCloud!=null && movieUserBillListCloud.size()>0){
                                List<TbMovieUserBill> exitMovieUserBillList=movieUserBillMapper.selectListBySQL(new TbMovieUserBill());
                                Map<String,TbMovieUserBill> exitMovieUserBillMap=new HashMap<>();
                                if(exitMovieUserBillList.size()>0){
                                    for(TbMovieUserBill bill:exitMovieUserBillList){
                                        exitMovieUserBillMap.put(bill.getOrderNo(),bill);
                                    }
                                }
                                List<TbMovieUserBill> newMovieUserBillList=new ArrayList<>();
                                for(TbMovieUserBill bill:movieUserBillListCloud)
                                {
                                    if(!exitMovieUserBillMap.containsKey(bill.getOrderNo()))
                                    {
                                        newMovieUserBillList.add(bill);
                                    }
                                }
                                if(newMovieUserBillList.size()>0)
                                {
                                    movieUserBillMapper.insertList(newMovieUserBillList);
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                result = true;
            }

        }catch (HttpException e){
            log.error(e.getMessage());
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return result;
    }

    @Override
    public boolean synUserShipToCloud() {
        boolean result=false;
        try{
            TbMovieServer movieServerModel=null;
            List<TbMovieServer> movieServerList=movieServerMapper.selectListBySQL(new TbMovieServer());
            if(movieServerList.size()>0){
                movieServerModel=movieServerList.get(0);
            }
            if(movieServerModel==null){
                log.error("movieServer is null...");
            }else{
                TbMovieUser movieUserModel = new TbMovieUser();
                List<TbMovieUser> movieUserList = movieUserMapper.selectListBySQL(movieUserModel);
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put("movieUserList", JSON.toJSONString(movieUserList));
                try {
                    HttpRequest request = HttpUtil.createPost(shoreCloudUrl + "/cloud/v1/synUserShipToCloud");
                    Map<String,Object> params=new HashMap<>();
                    params.put("appKey","movie12qwaszx34erdfcv");
                    params.put("appSecret","abc12332111223333");
                    params.put("keyWord",JSON.toJSONString(resultMap));
                    params.put("shipId",movieServerModel.getShipId());
                    request.form(params);
                    HttpResponse execute = request.execute();
                    if (!execute.isOk()) {
                        log.error("请求token失败,body={},execute={}", execute.body(), execute);
                    }
                    String resultString= UnicodeUtil.toString(execute.body());
                    if(CommonUtils.isNotBlank(resultString)){
                        AppV1Result appV1Result=JSON.parseObject(resultString,AppV1Result.class);
                        if(appV1Result.isSuccess()){
                            log.info("movieUserList success...");
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                result = true;
            }

        }catch (HttpException e){
            log.error(e.getMessage());
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return result;
    }

    @Override
    public boolean synFlowDataCloudToShip() {
        boolean result=false;
        try{
            TbMovieServer movieServerModel=null;
            List<TbMovieServer> movieServerList=movieServerMapper.selectListBySQL(new TbMovieServer());
            if(movieServerList.size()>0){
                movieServerModel=movieServerList.get(0);
            }
            if(movieServerModel==null){
                log.error("movieServer is null...");
            }else{
                Map<String, String> resultMap = new HashMap<>();
                try {
                    HttpRequest request = HttpUtil.createPost(shoreCloudUrl + "/cloud/v1/synFlowDataCloudToShip");
                    Map<String,Object> params=new HashMap<>();
                    params.put("appKey","movie12qwaszx34erdfcv");
                    params.put("appSecret","abc12332111223333");
                    params.put("keyWord",JSON.toJSONString(resultMap));
                    params.put("shipId",movieServerModel.getShipId());
                    request.form(params);
                    HttpResponse execute = request.execute();
                    if (!execute.isOk()) {
                        log.error("请求token失败,body={},execute={}", execute.body(), execute);
                    }
                    String resultString= UnicodeUtil.toString(execute.body());
                    if(CommonUtils.isNotBlank(resultString)){
                        AppV1Result appV1Result=JSON.parseObject(resultString,AppV1Result.class);
                        if(appV1Result.isSuccess()){
                            Map<String,Object> resultMp= (Map<String, Object>) appV1Result.getData();
                            String productListString=CommonUtils.parseStringData(resultMp.get("productList"));
                            List<TbProductInfo> productListCloud=JSON.parseArray(productListString,TbProductInfo.class);
                            //productList
                            if(productListCloud!=null){
                                productInfoMapper.deleteAll();
                                if(productListCloud.size()>0)
                                {
                                    productInfoMapper.insertList(productListCloud);
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                result = true;
            }

        }catch (HttpException e){
            log.error(e.getMessage());
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return result;
    }

    @Override
    public boolean synMovieShipToCloud() {
        boolean result=false;
        try{
            TbMovieServer movieServerModel=null;
            List<TbMovieServer> movieServerList=movieServerMapper.selectListBySQL(new TbMovieServer());
            if(movieServerList.size()>0){
                movieServerModel=movieServerList.get(0);
            }
            if(movieServerModel==null){
                log.error("movieServer is null...");
            }else{
                TbMovie movieModel = new TbMovie();
                List<TbMovie> movieList = movieMapper.selectListBySQL(movieModel);
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put("movieList", JSON.toJSONString(movieList));
                try {
                    HttpRequest request = HttpUtil.createPost(shoreCloudUrl + "/cloud/v1/synMovieShipToCloud");
                    Map<String,Object> params=new HashMap<>();
                    params.put("appKey","movie12qwaszx34erdfcv");
                    params.put("appSecret","abc12332111223333");
                    params.put("keyWord",JSON.toJSONString(resultMap));
                    params.put("shipId",movieServerModel.getShipId());
                    request.form(params);
                    HttpResponse execute = request.execute();
                    if (!execute.isOk()) {
                        log.error("请求token失败,body={},execute={}", execute.body(), execute);
                    }
                    String resultString= UnicodeUtil.toString(execute.body());
                    if(CommonUtils.isNotBlank(resultString)){
                        AppV1Result appV1Result=JSON.parseObject(resultString,AppV1Result.class);
                        if(appV1Result.isSuccess() && appV1Result.getData()!=null){
                            log.info("synMovieShipToCloud Success...");
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                result = true;
            }

        }catch (HttpException e){
            log.error(e.getMessage());
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return result;
    }

    @Override
    public boolean synMovieCloudToShip() {
        boolean result=false;
        try{
            TbMovieServer movieServerModel=null;
            List<TbMovieServer> movieServerList=movieServerMapper.selectListBySQL(new TbMovieServer());
            if(movieServerList.size()>0){
                movieServerModel=movieServerList.get(0);
            }
            if(movieServerModel==null){
                log.error("movieServer is null...");
            }else{
                Map<String, String> resultMap = new HashMap<>();
                try {
                    HttpRequest request = HttpUtil.createPost(shoreCloudUrl + "/cloud/v1/synMovieCloudToShip");
                    Map<String,Object> params=new HashMap<>();
                    params.put("appKey","movie12qwaszx34erdfcv");
                    params.put("appSecret","abc12332111223333");
                    params.put("keyWord",JSON.toJSONString(resultMap));
                    params.put("shipId",movieServerModel.getShipId());
                    request.form(params);
                    HttpResponse execute = request.execute();
                    if (!execute.isOk()) {
                        log.error("请求token失败,body={},execute={}", execute.body(), execute);
                    }
                    String resultString= UnicodeUtil.toString(execute.body());
                    if(CommonUtils.isNotBlank(resultString)){
                        AppV1Result appV1Result=JSON.parseObject(resultString,AppV1Result.class);
                        if(appV1Result.isSuccess()){
                            Map<String,Object> resultMp= (Map<String, Object>) appV1Result.getData();
                            String shipMovieListString=CommonUtils.parseStringData(resultMp.get("shipMovieList"));
                            List<TbMovie> shipMovieListCloud=JSON.parseArray(shipMovieListString,TbMovie.class);
                            //shipMovieList
                            if(shipMovieListCloud!=null && shipMovieListCloud.size()>0)
                            {
                                Long[] movieIdArray=new Long[shipMovieListCloud.size()];
                                for(int i=0;i<shipMovieListCloud.size();i++)
                                {
                                    movieIdArray[i]=shipMovieListCloud.get(i).getMovieId();
                                }
                                List<TbMovie> newMovieList=new ArrayList<>();
                                Map<Long,TbMovie> exitMovieMap=new LinkedHashMap<>();
                                List<TbMovie> exitMovieList=movieMapper.findMovieListByIds(movieIdArray);
                                if(exitMovieList.size()>0){
                                    for(TbMovie movieItem:exitMovieList){
                                        exitMovieMap.put(movieItem.getMovieId(),movieItem);
                                    }
                                }
                                for(int i=0;i<shipMovieListCloud.size();i++)
                                {
                                    TbMovie cloudMovie=shipMovieListCloud.get(i);
                                    if(!exitMovieMap.containsKey(cloudMovie.getMovieId())){
                                        newMovieList.add(cloudMovie);
                                    }
                                }
                                if(newMovieList.size()>0)
                                {
                                    movieMapper.insertList(newMovieList);
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                result = true;
            }

        }catch (HttpException e){
            log.error(e.getMessage());
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return result;
    }

    @Override
    public AdminV1Result autoShipDeviceLog(String logDate) {
        AdminV1Result result=new AdminV1Result();
        try {
            FileUtils.existOrmkdir(logDir);
            File[] fileList = FileUtil.ls(logDir);
            if (fileList.length > 0) {
                for(File file:fileList) {
                    String ipDir=file.getName();
                    if (Validator.isIpv4(ipDir) || Validator.isIpv6(ipDir)) {
                        File[] files = FileUtil.ls(file.getPath());
                        try  { // 获取目录下所有文件和目录的流
                            Arrays.sort(files, Comparator.comparing(File::getName).reversed());
                            log.info("ip["+ipDir+"]文件夹里最新文件："+files[0].getName()+"，目前logDate日期"+logDate);
                            File lastedLogFile=files[0];
                            if(CommonUtils.isNotBlank(logDate)){
                                lastedLogFile=new File(logDir+ipDir+File.separator+logDate+".log");
                            }
                            if(lastedLogFile.exists()){
                                //发送Email并发附件
                                try {
                                    String[] mailArray="bit@jinshengnetwork.com.cn;474986568@qq.com;shipip@126.com;chenjingguo@email.jinsyun.cn".split(";");
                                    if(mailArray.length>0){
                                        for(String to:mailArray){
                                            log.info("发送Email并发附件...");
                                            String from="cstelshipnet@163.com";
                                            String subject="【日志系统提醒】";
                                            String content="尊敬的【"+to+"】用户：您好，IP["+ipDir+"]的设备收到警告日志，详情看附件!";
                                            MailUtils.sendMail(to,from,subject, content,true,new File[]{lastedLogFile});
                                        }
                                    }
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


}
